import {computed, defineComponent, watch} from "vue";
import {useSize} from "element-plus";
import {useRequest} from "@/hooks";
import {buildRequestEntity} from "@/components/Form/util";

export default defineComponent({
  name: "DynamicSelector",
  props: {
    width: {
      type: String,
      default: '180px'
    },
    requestUrl: {
      type: String,
      default: '/smart/dict/getListByKey'
    },
    params: Object,
    dictKey: String,
    vKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'text'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    size: String,
    disableCache: {
      type: Boolean,
      default: true
    },
    optFormat: {
      type: Function,
      default: v => v
    },
    init: {
      type: Boolean,
      default: true
    }
  },
  setup(props, {attrs, slots, emit }) {
    const {vKey, labelKey, valueKey, disableCache, width, size, optFormat, init} = props
    const itemSize = useSize()
    const elSize = computed(() => size || itemSize.value)
    let {data} = init ? useRequest(buildRequestEntity(props), !disableCache) : {data:{value:[]}}
    let done = false
    watch(() => props.requestUrl, newVal => {
      if(init) return
      const reqParam = newVal.split('?')[1].split('=')[1]
      if(reqParam == 'undefined') return
      if(done) emit('update:modelValue', undefined)
      const res = useRequest(buildRequestEntity(props), !disableCache)
      data = res.data
      done = true
    }, { immediate: true })

    return () => (
        <el-select
            style={{width}}
            size={elSize.value}
            filterable={!attrs.readonly}
            clearable={!attrs.readonly}
            {...attrs}
        >
          {
            optFormat(data.value).map(item => (
                <el-option
                    disabled={attrs.readonly}
                    key={item[vKey]}
                    label={item[labelKey]}
                    value={item[valueKey]}>
                  {slots.default?.(item)}
                </el-option>
            ))
          }
        </el-select>
    )
  }
})
